﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using NPOI.XSSF.Model;
using IntelligentEscalator.BUS;
using IntelligentEscalator.Models;

namespace IntelligentEscalator.DAL
{
    public class OrganizationDAL
    {
        public List<OrganizationInfo> QueryOrganization(OrganizationInfo organizationInfo)
        {
            try
            {
                List<OrganizationInfo> list = new List<OrganizationInfo>();
                string strSql = "SELECT * FROM organization";
                string sqlwhere = string.Empty;

                if (!string.IsNullOrEmpty(organizationInfo.parentCode))
                {
                    sqlwhere += " parentCode=@parentCode AND";
                }
                else
                {
                    sqlwhere += " parentCode is NULL AND";
                }

                sqlwhere += " disabled=@disabled AND";

                if (sqlwhere.Length > 0)
                {
                    strSql += " where" + sqlwhere.Substring(0, sqlwhere.Length - 4);
                }

                using (MySqlConnection connection = DataFactory.GetMysqlConnection())
                {
                    MySqlCommand mySqlCommand = new MySqlCommand(strSql, connection);

                    // 添加参数
                    mySqlCommand.Parameters.AddWithValue("@parentCode", organizationInfo.parentCode);
                    mySqlCommand.Parameters.AddWithValue("@disabled", organizationInfo.disabled);
                    MySqlDataAdapter adapter = new MySqlDataAdapter(mySqlCommand);
                    DataSet dataSet = new DataSet();
                    adapter.Fill(dataSet);
                    DataTable dataTable = dataSet.Tables[0];
                    list = ToList<OrganizationInfo>(dataTable);
                }
                return list;
            }
            catch
            {
                return null;
            }
        }

        public int QueryOrganizationCount(OrganizationInfo organizationInfo)
        {
            string strSql = "SELECT COUNT(1) FROM organization";
            string sqlwhere = string.Empty;

            if (!string.IsNullOrEmpty(organizationInfo.type))
            {
                sqlwhere += " type='" + organizationInfo.type + "' AND";
            }
            if (!string.IsNullOrEmpty(organizationInfo.parentCode))
            {
                sqlwhere += " parentCode='" + organizationInfo.parentCode + "' AND";
            }
            else
            {
                sqlwhere += " parentCode is NULL AND";
            }

            if (!string.IsNullOrEmpty(organizationInfo.disabled))
            {
                sqlwhere += " disabled='" + organizationInfo.disabled + "' AND";
            }

            if (sqlwhere.Length > 0)
            {
                strSql += " where" + sqlwhere.Substring(0, sqlwhere.Length - 4);
            }

            return SqlHelper<OrganizationInfo>.SqlScalar(strSql);
        }

        public string AddOrganization(AuthOrganizationInfo authOrganization)
        {
            string strSql = string.Format(@"INSERT INTO organization(parentId,parentCode,code,name,disabled,organizationId)VALUES('{0}','{1}','{2}','{3}','{4}','{5}')"
                , authOrganization.parentId, authOrganization.parentCode, authOrganization.code, authOrganization.name, authOrganization.disabled, authOrganization.id);

            try
            {
                int count = SqlHelper<AuthOrganizationInfo>.SqlExecuteRows(strSql);

                if (count > 0)
                {
                    return "success";
                }
                return "fail";
            }
            catch (Exception e)
            {
                return "fail," + e.ToString();
            }
        }

        public string EditOrganization(AuthOrganizationInfo authOrganization)
        {
            string strSql = string.Format("UPDATE organization SET parentId='{0}',parentCode='{1}',code='{2}',name='{3}',disabled='{4}' WHERE organizationId='{5}'"
                , authOrganization.parentId, authOrganization.parentCode, authOrganization.code, authOrganization.name, authOrganization.disabled, authOrganization.id);

            if (SqlHelper<AuthOrganizationInfo>.SqlExecute(strSql))
            {
                return "success";
            }
            else
            {
                return "fail";
            }
        }

        public string EditOrganizationById(AuthOrganizationInfo authOrganization, int id)
        {
            string strSql = string.Format("UPDATE organization SET parentId='{0}',parentCode='{1}',code='{2}',name='{3}',disabled='{4}', organizationId='{5}' WHERE id={6}"
                , authOrganization.parentId, authOrganization.parentCode, authOrganization.code, authOrganization.name, authOrganization.disabled, authOrganization.id, id);

            if (SqlHelper<AuthOrganizationInfo>.SqlExecute(strSql))
            {
                return "success";
            }
            else
            {
                return "fail";
            }
        }

        public string DelOrganization(AuthOrganizationInfo authOrganization)
        {
            string strSql = string.Format("delete FROM organization WHERE organizationId='{0}'", authOrganization.id);

            try
            {
                int count = SqlHelper<AuthOrganizationInfo>.SqlExecuteRows(strSql);
                if (count > 0)
                {
                    return "success";
                }
                return "fail";
            }
            catch (Exception e)
            {
                return "fail," + e.ToString();
            }
        }

        public List<T> ToList<T>(DataTable dt) where T : class, new()
        {
            List<T> list = new List<T>();
            //确认参数有效,若无效则返回Null
            if (dt == null)
                return list;
            else if (dt.Rows.Count == 0)
                return list;
            Dictionary<string, string> dicField = new Dictionary<string, string>();
            Dictionary<string, string> dicProperty = new Dictionary<string, string>();
            Type type = typeof(T);

            //创建字段字典，方便查找字段名
            foreach (var item in type.GetFields())
            {
                dicField.Add(item.Name.ToLower(), item.Name);
            }
            //创建属性字典，方便查找属性名
            foreach (var item in type.GetProperties())
            {
                dicProperty.Add(item.Name.ToLower(), item.Name);
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //创建泛型对象
                T _t = Activator.CreateInstance<T>();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string memberKey = dt.Columns[j].ColumnName.ToLower();

                    //字段赋值
                    if (dicField.ContainsKey(memberKey))
                    {
                        FieldInfo theField = type.GetField(dicField[memberKey]);
                        var dbValue = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                            dbValue = null;
                        if (dbValue != null)
                        {
                            Type memberType = theField.FieldType;
                            //dbValue = dbValue.ChangeType(memberType);
                            dbValue = Convert.ChangeType(dbValue, memberType);
                        }
                        theField.SetValue(_t, dbValue);
                    }
                    //属性赋值
                    if (dicProperty.ContainsKey(memberKey))
                    {
                        PropertyInfo theProperty = type.GetProperty(dicProperty[memberKey]);
                        if (!theProperty.CanWrite) continue;
                        var dbValue = dt.Rows[i][j];
                        if (dbValue.GetType() == typeof(DBNull))
                            dbValue = null;
                        if (dbValue != null)
                        {
                            Type memberType = theProperty.PropertyType;
                            if (memberType.IsGenericType && memberType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                            {
                                NullableConverter newNullableConverter = new NullableConverter(memberType);
                                dbValue = newNullableConverter.ConvertFrom(dbValue);
                            }
                            else
                            {
                                dbValue = Convert.ChangeType(dbValue, memberType);
                            }
                        }
                        theProperty.SetValue(_t, dbValue, null);
                    }
                }
                list.Add(_t);
            }
            return list;
        }

        public int QuerySyncOrganizationId(string organizationId)
        {
            string strSql = "SELECT id FROM organization where organizationId='" + organizationId + "'";

            return SqlHelper<OrganizationInfo>.SqlScalar(strSql);
        }
    }
}
